/*
 *   Copyright 2006 Wei Lian <lianwei3@gmail.com>
 *
 *   This program is free software; you can redistribute it and/or
 *   modify it under the terms of the GNU General Public License
 *   as published by the Free Software Foundation; either version 2
 *   of the License, or (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

#include "header.h"
#define READ_BUF_SIZE 256

long
find_pid_by_name (char *pidName)
{
  DIR *dir;
  struct dirent *next;

  dir = opendir ("/proc");
  if (!dir)
    {
      fprintf (stderr, "Cannot open /proc\n");
      exit (1);
    }

  while ((next = readdir (dir)) != NULL)
    {
      FILE *status;
      char filename[READ_BUF_SIZE];
      char buffer[READ_BUF_SIZE];

      if (strcmp (next->d_name, "..") == 0)
	continue;

      if (!isdigit (*next->d_name))
	continue;

      sprintf (filename, "/proc/%s/cmdline", next->d_name);
      if (!(status = fopen (filename, "r")))
	{
	  continue;
	}

      int n;
      if ((n = fread (buffer, 1, sizeof buffer, status)) == 0)
	{
	  fclose (status);
	  continue;
	}
      fclose (status);

      while (char *ptr = (char *)memchr (buffer, 0, n - 1))
	*ptr = ' ';
      if (strstr (buffer, pidName))
	{
	  closedir (dir);
	  return strtol (next->d_name, NULL, 0);
	}
    }
  closedir (dir);
  return 0;
}
